﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace LogoFX.Infra.Interactivity
{
    //TODO: the interface probably should be moved to some common place - need to discuss.

    /// <summary>
    /// Represents the common interface for style selector.
    /// </summary>
    public interface IStyleSelector
    {
        /// <summary>
        /// Selects the style for specified <see cref="FrameworkElement"/> instance.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="container">The container of specified element.</param>
        /// <returns></returns>
        Style SelectStyle(FrameworkElement element, DependencyObject container);
    }

    /// <summary>
    /// Gives the ability to <see cref="DataGrid"/> control to select row style, by using 
    /// provided <see cref="IStyleSelector"/>.
    /// </summary>
    public class DataGridRowStyleSelectorBehavior : Behavior<DataGrid>
    {
        #region Dependency Properties

        public static readonly DependencyProperty StyleSelectorProperty =
            DependencyProperty.Register(
                "StyleSelector",
                typeof(IStyleSelector),
                typeof(DataGridRowStyleSelectorBehavior),
                new PropertyMetadata(null));

        /// <summary>
        /// Gets or sets the row style selector.
        /// </summary>
        /// <value>
        /// The row style selector.
        /// </value>
        public IStyleSelector StyleSelector
        {
            get { return (IStyleSelector)GetValue(StyleSelectorProperty); }
            set { SetValue(StyleSelectorProperty, value); }
        }

        #endregion

        /// <summary>
        /// Called after the behavior is attached to an AssociatedObject.
        /// </summary>
        protected override void OnAttached()
        {
            base.OnAttached();

            DataGrid grid = AssociatedObject;
            grid.LoadingRow += OnLoadingRow;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            DataGrid grid = AssociatedObject;
            grid.LoadingRow -= OnLoadingRow;
        }

        /// <summary>
        /// Called when [loading row].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Controls.DataGridRowEventArgs"/> instance containing the event data.</param>
        private void OnLoadingRow(object sender, DataGridRowEventArgs e)
        {
            if(StyleSelector != null)
            {
                Style style = StyleSelector.SelectStyle(e.Row, AssociatedObject);

                if(style != null)
                    e.Row.Style = style;
            }
        }
    }
}
